<template>
  <div >
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="add">新增</a-button>
    </div>
    <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
      <i class="anticon anticon-info-circle ant-alert-icon" />
      已选择
      <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>
      项
      <a style="margin-left: 24px"  @click="onClearSelected">清空</a>
    </div>
    <a-table
      size="middle"
      bordered
      row-key="id"
      :columns="columns"
      :data-source="data_"
      :pagination="ipagination"
      :loading="loading"
      :row-selection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
      @change="handleTableChange"
    >
      <template slot="action" slot-scope="text, record">
      <a @click="handleEdit(record)">编辑</a>
      <a-divider type="vertical" />
      <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
        <a >删除</a>
      </a-popconfirm>
      </template>
    </a-table>
    <!--弹窗区域  -->
    <j-modal
      :width="1000"
      :title="title"
      :visible.sync="editModalVisible"
      @cancel="handleCancleDbSync"
      :fullscreen.sync="fullscreen"
      :switch-fullscreen="true"
      :maskClosable="false"
    >
      <template slot="footer">
        <a-button @click="handleCancleDbSync">关闭</a-button>
        <a-button type="primary" @click="handleDbSync" >确定</a-button>
      </template>
      <div class="table-page-search-wrapper">
        <a-form layout="horizontal" ref="ruleForm" :form="form" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-row :gutter="24">
            <a-col :xl="24" :lg="24" :md="24" :sm="24">
              <a-form-item label="唯一编码">
                <a-input placeholder="请输入唯一编码" v-decorator="['relationCode', { rules: rules.relationCode }]"/>
              </a-form-item>
            </a-col>
            <a-col :xl="24" :lg="24" :md="24" :sm="24">
              <a-form-item label="业务主表">
                <a-select
                  v-decorator="[
                    'table',
                    { rules: rules.table },
                  ]"
                  placeholder="请选择业务主表"
                  show-search
                  :filter-option="filterOption"
                  @change="tableChange"
                >
                  <a-select-option v-for="item in tableList" :key="item.tableName">{{item.tableTxt}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="24" :lg="24" :md="24" :sm="24">
              <a-form-item label="是否分组">
                <a-checkbox v-decorator="['isGroup',{ valuePropName: 'checked' }]"/>
              </a-form-item>
            </a-col>
            <a-col :xl="24" :lg="24" :md="24" :sm="24" >
              <a-form-item label="分组表达式">
                <a-input placeholder="请输入分组表达式" v-decorator="['titleExp', { rules: rules.titleExp }]"/>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <!-- 操作按钮区域 -->
          <div class="table-operator">
            <a-button type="primary" icon="plus" @click="handleAddSubList">新增</a-button>
            <a-popconfirm v-if="selectedSubRowKeys.length" :title="'确定要删除这'+selectedSubRowKeys.length+'项吗?'" @confirm="() => handleRmoveSubList()">
              <a-button icon="minus" >删除</a-button>
            </a-popconfirm>
          </div>
        <!--  主表、附表具体字段转换规则-->
        <a-form layout="horizontal" ref="subform" :form="subform">
          <a-table
            size="middle"
            bordered
            :rowKey="(record, index) => index"
            :columns="subColumns"
            :data-source="dataSource"
            :pagination="false"
            :row-selection="{selectedRowKeys: selectedSubRowKeys, onChange: onSelectSubChange}"
            :scroll="getScroll"
          >
            <template slot="input" slot-scope="text, record, index, column">
              <a-form-item >
                <a-input style="margin: -5px 0" v-decorator="[column.key,{ rules: column.validateRules || [] }]"/>
              </a-form-item>
            </template>
            <template slot="select" slot-scope="text, record, index, column">
              <a-form-item >
                <a-select
                  v-decorator="[column.key,{ rules: column.validateRules || [] }]"
                  :placeholder="column.placeholder"
                >
                  <a-select-option
                    v-for="(option,i) in column.options"
                    :key="i"
                    :value="option.value"
                  >
                    {{option.title}}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </template>
            <template slot="input_pop" slot-scope="text, record, index, column">
              <a-form-item >
                <j-input-pop style="margin: -5px 0" v-decorator="[column.key,{ rules: column.validateRules || [] }]"></j-input-pop>
              </a-form-item>
            </template>
          </a-table>
        </a-form>
      </div>
    </j-modal>
  </div>
</template>
<script>
import { postAction, putAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { validateDuplicateValue } from '@/utils/util'
import JEditableTable from '@/components/jeecg/JEditableTable'
import { FormTypes } from '@/utils/JEditableTableUtil'
import { getAction } from '@/api/manage'
import JInputPop from '@/components/jeecg/minipop/JInputPop'
export default {
  name: 'processPostposition',
  components: {
    JEditableTable,
    JInputPop
  },
  mixins: [JeecgListMixin],
  data() {
    return {
      url: {
        list: '/online/cgform/head/list',
        edit: 'diagram/diagramConfiguration/edit',
        add: 'diagram/diagramConfiguration/add',
        tableList: '/form/formConfiguration/list', // online在线表单路径
        subList: '/form/formConfiguration/sublist'
      },
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '唯一编码',
          align: 'center',
          dataIndex: 'relationCode'
        },
        {
          title: '业务主表',
          align: 'center',
          dataIndex: 'table'
        },
        {
          title: '是否分组',
          align: 'center',
          dataIndex: 'isGroup'
        },
        {
          title: '分组表达式',
          align: 'center',
          dataIndex: 'titleExp'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      title: '新增',
      fullscreen: false,
      data_: [{}],
      labelCol: { span: 5 },
      wrapperCol: { span: 19 },
      editModalVisible: false,
      newFormData: {// 新增用数据
        'relationCode': '',
        'isGroup': true,
        'titleExp': ''
      },
      form: this.$form.createForm(this),
      subform: this.$form.createForm(this),
      rules: {
        relationCode: [
          { required: true, message: '请输入唯一编码', trigger: 'change' },
          { validator: (rule, value, callback) => validateDuplicateValue('cs_diagram_config', 'code', value, this.form.getFieldValue('id'), callback) }
        ],
        table: [
          { required: true, message: '请选择业务主表', trigger: 'change' }
        ],
        titleExp: [
          { validator: (rule, value, callback) => {
            if (!value && this.form.getFieldValue('isGroup')) {
              callback('请输入分组表达式')
            } else {
              callback()
            }
          } }
        ]
      },
      loading: false,
      dataSource: [],
      subColumns: [
        {
          title: '业务子表',
          align: 'center',
          key: 'subTable',
          width: '150px',
          scopedSlots: { customRender: FormTypes.select },
          options: [
            { title: '普通查询', value: 'single' },
            { title: '范围查询', value: 'group' }
          ],
          defaultValue: '',
          placeholder: '请选择业务子表'
        },
        {
          title: '业务主表/子表字段',
          align: 'center',
          key: 'field',
          width: '150px',
          scopedSlots: { customRender: FormTypes.select },
          options: [],
          defaultValue: '',
          placeholder: '请选择业务主表/子表字段',
          validateRules: [{ required: true, message: '业务主表/子表字段不能为空', trigger: 'blur' }]
        },
        {
          title: '流程/节点表单',
          align: 'center',
          key: 'nodeTable',
          width: '150px',
          defaultValue: '',
          scopedSlots: { customRender: FormTypes.select },
          options: [
            { title: '普通查询', value: 'single' },
            { title: '范围查询', value: 'group' }
          ],
          placeholder: '请选择流程/节点表单'
        },
        {
          title: '流程/节点字段',
          key: 'nodeField',
          width: '150px',
          scopedSlots: { customRender: FormTypes.select },
          options: [],
          defaultValue: 'single',
          placeholder: '请选择流程/节点表单'
        },
        {
          title: '聚合类型',
          align: 'center',
          key: 'aggregateType',
          width: '120px',
          scopedSlots: { customRender: FormTypes.select },
          defaultValue: '',
          placeholder: ''
        },
        {
          title: '表达式',
          align: 'center',
          key: 'func',
          width: '150px',
          scopedSlots: { customRender: FormTypes.input_pop },
          defaultValue: '',
          placeholder: ''
        },
        {
          title: '默认值',
          align: 'center',
          key: 'defValue',
          width: '150px',
          scopedSlots: { customRender: FormTypes.input },
          defaultValue: '',
          placeholder: ''
        }
      ],
      tableList: [], // 全部主表信息
      subTableList: [], // 附表信息
      selectedSubRowKeys: []
    }
  },
  computed: {
    getScroll() {
      if (this.dataSource.length >= 5) {
        return { y: 200, x: 1600 }
      } else {
        return { x: 1600 }
      }
    }
  },
  methods: {
    add() {
      this.editModalVisible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(this.newFormData)
      })
    },
    handleCancleDbSync() { // 关闭
      this.editModalVisible = false
    },
    handleDbSync() { // 弹窗点击确定
      this.subform.validateFields((valid, values) => {
        console.log('------', valid)
      })
      this.form.validateFields((valid, values) => {
        console.log(this.form.getFieldsValue())
        if (!valid) {
          this.updateData()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    updateData(params) { // 保存提交数据
      if (this.form.getFieldsValue('id')) {
        putAction(this.url.edit, this.form.getFieldsValue()).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.editModalVisible = false
            this.$emit('modalFormOk')
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          // this.loading = false
        })
      } else {
        postAction(this.url.add, this.form.getFieldsValue()).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.editModalVisible = false
            this.$emit('modalFormOk')
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          // this.loading = false
        })
      }
    },
    getSubList(parm, key) { // 请求附表数据
      getAction(this.url.subList, parm).then((res) => {
        // if (res.success) {
        //   this[key] = res.result
        // }
        // if (res.code === 510) {
        //   this.$message.warning(res.message)
        // }
      })
    },
    getOnlineFormList() { // 请求主表数据
      getAction(this.url.tableList, { tableTypes: '1,2' }).then((res) => {
        if (res.success) {
          this.tableList = res.result
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
      })
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    onSelectSubChange(selectedRowKeys) {
      this.selectedSubRowKeys = selectedRowKeys
    },
    handleAddSubList() {

    },
    handleRmoveSubList() {

    },
    tableChange(value) {
      console.log(value)
    }
  },
  mounted() {
    this.getOnlineFormList()
  }
}
</script>
<style scoped>
.ant-form-item{
    margin-bottom: 0px !important;
  }
</style>
